package xyz.zq.validation.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@ControllerAdvice
public class MyControllerExceptionHandler {

    @ExceptionHandler({MyException.class})
    @ResponseBody
    @ResponseStatus
    public Map<String, Object> handlerMyException(MyException myException) {
        BindingResult result = myException.getBindingResult();
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> lm = new ArrayList<>();
        List<FieldError> fieldErrors = result.getFieldErrors();
        fieldErrors.forEach(item -> {
            Map<String, Object> m = new HashMap<>();
            String field = item.getField();
            String defaultMessage = item.getDefaultMessage();
            m.put("field", field);
            m.put("defaultMessage", defaultMessage);
            lm.add(m);
        });
        map.put("errors", lm);
        map.put("msg", "参数检验错误");
        map.put("code", 500);
        return map;
    }
}
